<?php
/**
 * Created by PhpStorm.
 * User: zhulei
 * Date: 2020/1/24
 * Time: 下午8:11
 */

namespace  App\HttpController\Api\User;

use App\HttpController\Api\ApiBase;
use App\Model\UserModel;
use EasySwoole\Http\Message\Status;


class UserBase extends  ApiBase {

    protected $who;

    //session的cookie的头
    protected $sessionKey = 'userSession';

    //白名单
    protected  $whiteList = ['login, register'];

    /**
     * onRequest
     * @param null|string $action
     * @return bool|null
     * @throws \Throwable
     */
    function onRequest(?string $action): ?bool
    {
        if (parent::onRequest($action)) {
            //白名单判断
            if (in_array($action, $this->whiteList)) {
                return true;
            }
            //获取登入信息
            if (!$data = $this->getWho()) {
                $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
                return false;
            }
            //刷新cookie存活
            $this->response()->setCookie($this->sessionKey, $data->userSession, time() + 3600, '/');

            return true;
        }
        return false;
    }

    /**
     * getWho
     */
    function getWho(): ?UserModel
    {
        if ($this->who instanceof UserModel) {
            return $this->who;
        }
        $sessionKey = $this->request()->getRequestParam($this->sessionKey);
        if (empty($sessionKey)) {
            $sessionKey = $this->request()->getCookieParams($this->sessionKey);
        }
        if (empty($sessionKey)) {
            return null;
        }
        $userModel = new UserModel();
        $userModel->userSession = $sessionKey;
        $this->who = $userModel->getOneBySession();
        return $this->who;
    }


}